package com.example.testapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.Toast;

public class eventBack extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_back);
    }

    private boolean exit = false; // 标识是否可以退出
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                exit = false;
            }
        }
    };

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){
             if(!exit){
                 exit = true;
                 Toast.makeText(this, "再按一次就退出应用", Toast.LENGTH_SHORT).show();
                 // 发消息延迟2s将exit= false
                 handler.sendEmptyMessageDelayed(1,2000);
                 return true;
             }
        }
        return super.onKeyUp(keyCode, event);
    }
}